package ua.amsoft.brelok.filter;

import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;

/**
 * @author tair
 */
public class EditTextMinMaxValueInputFilter implements InputFilter {
    
    private final int minVal, maxVal;
    
    /**
     * Constructor
     * 
     * @param min - min value for field
     * @param max - max value for field
     */
    public EditTextMinMaxValueInputFilter(final int min, final int max) {
        this.minVal = min;
        this.maxVal = max;
    }
    
    /**
     * Constructor
     * 
     * @param min - min value for field
     * @param max - max value for field
     */
    public EditTextMinMaxValueInputFilter(final String min, final String max) {
        this.minVal = Integer.parseInt(min);
        this.maxVal = Integer.parseInt(max);
    }
    
    @Override
    public CharSequence filter(final CharSequence source, final int start, final int end,
            final Spanned dest, final int dstart, final int dend) {
        try {
            final int input = Integer.parseInt(dest.toString() + source.toString());
            if (isInRange(this.minVal, this.maxVal, input)) {
                return null;
            }
        } catch (final NumberFormatException e) {
            Log.e("DaysBeforeInputFilter", e.getLocalizedMessage());
        }
        return "";
    }
    
    /**
     * @param minValue - min value
     * @param maxValue - max value
     * @param userValue - user input value
     * @return true or false
     */
    private boolean isInRange(final int minValue, final int maxValue, final int userValue) {
        return maxValue > minValue ? (userValue >= minValue) && (userValue <= maxValue)
                : (userValue >= maxValue) && (userValue <= minValue);
    }
    
}
